package top.xinsix.est.controller;

import top.xinsix.est.tools.FileUtils;
import top.xinsix.est.tools.Result;
import top.xinsix.est.tools.ResultUtils;
import top.xinsix.est.tools.oss.OssUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;

@RequestMapping("/api/oss")
@RestController
public class OssController {
    @Autowired
    private OssUtils ossUtils;
    //上传
    @PostMapping("upload")
    public Result upload(MultipartFile file){
        try {
            //获取文件名
            String fileName=file.getOriginalFilename();
            //调用MultipartFile对象转换为File对象
            File newFile= FileUtils.MultipartFileToFile(file);
            String filePath = "est/model/phone/iphone/";
            ossUtils.uploadByStream(newFile,filePath+fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtils.returnFail("文件上传失败");
        }
        return ResultUtils.returnSuccess();
    }
    //下载
    @PostMapping("/download")
    public Result download(String fileId, String fileName, HttpServletResponse response){
        try {
            ossUtils.download(fileId,fileName,response);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtils.returnFail("文件下载失败");
        }
        return ResultUtils.returnSuccess();
    }
    //删除
    @PostMapping("/del")
    public Result del(String fileName){
        try {
            ossUtils.deleteFile(fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtils.returnFail("文件删除失败");
        }
        return ResultUtils.returnSuccess();
    }
}

